/**
 * @description:混入对象
 */
import tableColumn from "@/components_yy/tableColumn";
import tableApi from "@/api/basic-info-manage/table-config";
import axios from 'axios'
const service = axios.create()
service.defaults.timeout = 3000 * 60

export const mymixin = {
  components: { tableColumn },
  data() {
    return {
      dialogTableColumnVisible: false,
      nowpage: 1,
      loading: true,
      // 输入框是否可修改true为可修改
      canInput: false,
      // 添加删除修改状态---主要通过此状态来判断调用方法
      nowChanceStau: '',
      // 操作按钮的逻辑及展示数据
      addActive: true,
      delActive: false,
      saveActive: false,
      cancelActive: false,
      editActive: false,
      dialogFormVisible: false,
      // 表格数据
      tableData: [],
      // 表单数据
      formData: {},
      treeData: [],
      image: null,
      // 当前页
      currentPage: 1,
      // 每页的数据条数
      pageSize: 10,
      // 总条数
      totalSize: 0,
      // 总页数
      totalPages: 0,
      allPointList: [],
      rightTableData: [],
      // 特殊
      ExamineForm: {},
      ExamineTable: [],
      unitTypeId: '',
      unitsList: [],
      deleteFlag: true,
      tagsList: [],
      addformData: {},
      rules: {},
      postName: "",
      pictureId: '',
      token: "",
      InImgUrl: '',
      funcAppAuthActive: false,
      dateActive: '',
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        },
        {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        },
        {
          text: '最近一年',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
            picker.$emit('pick', [start, end]);
          }
        }
        ]
      },
      // 地址选择
      selectedOptions: [],
      address: "",
      // 弹出框添加修改
      titleText: null,
      currentRow: null,
      imgList: [],
      esname: '',
      List: {}
    }
  },
  created() {
    this.tableColumn && (this.allTableColumn = [...this.tableColumn])
    this.token = sessionStorage.getItem("token");
  },
  watch: {
    nowChanceStau(newval) {
      // 当状态为删除的时候触发删除方法---另外的删除修改添加，通过点击保存，调用方法来实现
      if (newval === 'del') {
        this.delmessage('formData')
      }
    }
  },
  computed: {
    headers() {
      return {
        "accessToken": sessionStorage.getItem("token"),
        "organizationNo": sessionStorage.organizationNo,
        "organizationList": sessionStorage.organizationList,
        "databaseName": sessionStorage.databaseName,
        "virtualSystemNo": sessionStorage.virtualSystemNo,
        "sysDataBaseName": "DB_TDW1_OM1"
      }
    }
  },
  mounted () {
    this.loadSaveColumn()
  },
  methods: {
    // 时间
    dateFn (i) {
      this.dateActive = i;
      if (i == 1) {
        const end = new Date();
        let start = new Date();
        start = start.getTime() - 3600 * 1000 * 24 * 7;
        this.searchlist.date = [start, end];
      } else if (i == 2) {
        const end = new Date();
        let start = new Date();
        start = start.getTime() - 3600 * 1000 * 24 * 30;
        this.searchlist.date = [start, end];
      } else if (i == 3) {
        const end = new Date();
        let start = new Date();
        start = start.getTime() - 3600 * 1000 * 24 * 90;
        this.searchlist.date = [start, end];
      }
      this.search()
    },
    dateChange () {
      this.dateActive = '';
      this.search()
    },
    dateClear () {
      this.dateActive = '';
      delete this.searchlist.date;
      this.search()
    },
    search(searchlist) {
      searchlist && (this.searchlist = searchlist)
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    // 导出
    async downloadExcel(url, param, file) {
      this.loading = true;
      if(url === 'v3/iot/dataItem/export') {
        const { data: data } = await service({
          method: "post",
          url: this.$baseurl.webServiceUrl + url,
          'responseType': "blob",
          headers: {
            'accessToken': sessionStorage.token,
            'databaseName': sessionStorage.databaseName,
            'organizationList': sessionStorage.organizationList,
            'organizationNo': sessionStorage.organizationNo,
            'virtualSystemNo': sessionStorage.virtualSystemNo
          },
          data: param.entity || param
        })
        this.loading = false;
        const link = document.createElement("a");
        link.download = file;
        link.style.display = "none";
        link.href = URL.createObjectURL(data);
        document.body.appendChild(link);
        link.click();
        URL.revokeObjectURL(link.href);
        document.body.removeChild(link);
      } else {
        const { data: data } = await axios({
          method: "post",
          url: this.$baseurl.webServiceUrl + url,
          'responseType': "blob",
          headers: {
            'accessToken': sessionStorage.token,
            'databaseName': sessionStorage.databaseName,
            'organizationList': sessionStorage.organizationList,
            'organizationNo': sessionStorage.organizationNo,
            'virtualSystemNo': sessionStorage.virtualSystemNo
          },
          data: param.entity || param
        })
        this.loading = false;
        const link = document.createElement("a");
        link.download = file;
        link.style.display = "none";
        link.href = URL.createObjectURL(data);
        document.body.appendChild(link);
        link.click();
        URL.revokeObjectURL(link.href);
        document.body.removeChild(link);
      }
    },
    // 列配置
    showColumn () {
      this.dialogTableColumnVisible = true
    },
    saveColumn () {
      this.$refs.tableColumn && this.$refs.tableColumn.save()
    },
    cancelColumn (reload) {
      this.dialogTableColumnVisible = false
      reload && this.loadSaveColumn()
    },
    loadSaveColumn() {
      let path = this.$route.path
      // if (['/production-batch-query', '/create-production-batch'].includes(path)) {
      //   path = path + this.batchType
      // }
      tableApi.queryByUrlAndAccountAndOrganizationNo(path).then(res => {
        let fieldContentStr = res.data?.fieldContentStr;
        let fieldContent = fieldContentStr && JSON.parse(fieldContentStr);
        if (fieldContent) {
          let tableColumn = []
          fieldContent.map(el => {
            let index = this.allTableColumn.findIndex(ele => {
              return ele.prop === el.prop
            })
            el.show && tableColumn.push(this.allTableColumn[index])
          })
          this.tableColumn = tableColumn
        }
      })
    },
    // 排序
    changeTableSort(column) {
      this.sortList = column.order ? [
        { property: column.prop, direction: column.order == "ascending" ? 'asc' : 'desc' }
      ] : []
      this.getTableDataList()
    },
    // 填充表格空白行
    addblankmet() {
      let havline = this.tableData.length % this.pageSize
      if (this.tableData.length < this.pageSize) {
        if (havline < this.pageSize) {
          const remain = this.pageSize - havline;
          for (var i = 0; i < remain; i++) {
            this.tableData.push({
              'index': i + this.tableData.length + 1
            });
          }
        }
      }
    },
    handleCurrentChange(val) {
      this.currentRow = val;
    },
    // 添加
    add(formData,b) {
      if(b==='queryDataList') {
        this.queryDataList()
      }
      this.canInput = true;
      this.nowChanceStau = 'add'
      this.formData = {}
      this.List = {}
      this.image = null;
      this.tagsList = [];
      this.unitTypeId = ''
      this.unitsList = []
      this.postName = ""
      this.InImgUrl = ''
      this.titleText = "添加"
      this.nowtopList = []
      this.nowbottomList = []
      this.dialogFormVisible = true;
      if (formData) {
        this.$nextTick(() => {
          this.$refs['formData']?.resetFields();
          this.$refs['formData']?.clearValidate()
          this.$set(this,'formData',{})
        })
      }
      this.addActive = false;
      this.delActive = false;
      this.saveActive = true;
      this.cancelActive = true;
      this.editActive = false;
      this.handleAdd && this.handleAdd(formData,b)
    },
    // 修改
    edit(data) {
      this.nowChanceStau = 'edit'
      this.titleText = "修改"
      this.dialogFormVisible = true;
      this.canInput = true;
      this.addActive = false;
      this.delActive = false;
      this.saveActive = true;
      this.cancelActive = true;
      this.editActive = false
      data && this.handleEdit && this.handleEdit(data)
    },
    // 删除
    del() {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          this.nowChanceStau = 'del'
          // this.resetActionBar()
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
          // this.resetActionBar()
          if (this.tableData.length > 0) {
            // alert(1)
            this.$refs.tableData.clearSelection();
          } else if (this.treeData.length > 0) {
            this.$refs.tree.setCheckedKeys([]);
          }
          // this.resetActionBar();
        });
      this.formData = {}
      this.List = {}
      this.postName = ""
      this.nowChanceStau = "";
      this.canInput = true;
      this.addActive = true;
      // this.delActive = false;
      this.saveActive = false;
      this.editActive = false
      this.cancelActive = false;
    },
    // 取消
    cancel(formData) {
      this.deleteFlag = true;
      this.nowChanceStau = '';
      this.formData = {};
      this.List = {};
      this.nowfilterType = ''
      this.pictureId = '';
      this.rightTableData = [];
      this.tagsList = [];
      this.selectedOptions = [];
      this.unitTypeId = ''
      this.unitsList = []
      this.postName = ""
      this.address = "";
      this.dialogFormVisible = false;
      this.addformData = {}
      this.InImgUrl = ''
      this.imgList = [];
      this.NotifierList = [ {
        userName: "",
        personNo: "",
        phoneFlag: false,
        weChatFlag: false,
        emailFlag: false,
        cidFlag: false,
        radio: 3
      }]
      // TODO:king
      this.nowalarmTemplateId = ''
      this.canInput = false;
      this.addActive = true;
      this.delActive = false;
      this.saveActive = false;
      this.cancelActive = false;
      this.editActive = false;
      this.dialogNoticeFormVisible = false
      if (formData) {
        // console.log(formData)
        this.$refs['formData']?.resetFields();
        this.$refs['tableData']?.setCurrentRow()
      }
    },
    // 初始化操作栏状态
    resetActionBar() {
      this.nowChanceStau = ''
      this.formData = {}
      this.rightTableData = []
      this.image = null;
      this.pictureId = ''
      this.unitTypeId = ''
      this.unitsList = []
      this.InImgUrl = ''
      this.postName = ""
      this.canInput = false;
      this.dialogFormVisible = false;
      this.funcAppAuthActive = false
      this.addActive = true;
      this.delActive = false;
      this.imgList = [];

      this.saveActive = false;
      this.cancelActive = false;
      this.editActive = false
    },
    setOptions (config, field, option) {
      let index = config.findIndex(el => {
        return el.prop === field
      })
      index !== -1 && (config[index].options = option)
    }
  }
}
